import { action, observable, configure, computed } from 'mobx'
import request from '../utils/request'

configure({ enforceActions: 'observed' })

class MainStore {
  constructor(rootStore) {
    this.rootStore = rootStore
  }
  @observable state = {
    list: [],
  }

  /**
   * 获取所有数据
   */
  @action.bound async getTodos() {
    const { data } = await request.get('/')
    this.setTodos(data)
  }
  @action.bound setTodos(data) {
    this.state.list = data
  }
  /**
   * 删除数据
   * @param {number} id
   */
  @action.bound async delTodo(id) {
    await request.delete(`/${id}`)
    await this.getTodos()
  }

  /**
   * 更新数据
   * @param {number} id
   * @param {string} key 更新谁
   * @param {string} value 更新为什么
   */
  @action.bound async updateTodo(id, key, value) {
    await request.patch(`/${id}`, { [key]: value })
    await this.getTodos()
  }
  /**
   * 添加数据
   * @param {string} name
   */
  @action.bound async addTodo(name) {
    await request.post('/', { name, done: false })
    await this.getTodos()
  }
  /**
   * 全选按钮的状态
   */
  @computed get mainRadioStatus() {
    return this.state.list.every((item) => item.done)
  }
  /**
   * 更新所有按钮的状态
   * @param {boolean} done
   */
  @action.bound async upatePerRadioStatus(done) {
    const arrPromise = this.state.list.map((item) => {
      return this.updateTodo(item.id, 'done', done)
    })
    await Promise.all(arrPromise)
    await this.getTodos()
  }
  /**
   * 已完成的数据
   */
  @computed get completed() {
    return this.state.list.filter((item) => item.done)
  }
  /**
   * 清空已完成
   */
  @action.bound async clearCompleted() {
    const arrPromise = this.completed.map((item) => {
      return request.delete(`/${item.id}`)
    })
    await Promise.all(arrPromise)
    await this.getTodos()
  }
  @computed get unCompleted() {
    return this.state.list.filter((item) => !item.done)
  }

  @computed get renderList() {
    // 根据 footerStore 模块的 active 来从 this.state.list 中得到对应的结果
    const active = this.rootStore.footerStore.state.active
    /* if (active === 'Active') {
      return this.unCompleted
    } else if (active === 'Completed') {
      return this.completed
    } */
    return active === 'Active' ? this.unCompleted : active === 'Completed' ? this.completed : this.state.list
  }
}
export default MainStore
